package server.qiang.Process;

import common.harvin.potocol.Request;
import common.harvin.potocol.Response;
import server.qiang.database.database;
import server.qiang.email.MultiMailsender;
import server.qiang.email.MultiMailsender.MultiMailSenderInfo;

import java.sql.SQLException;

public class SendEmail {

	public static Response sendemail(Request request) {
		System.out.println("command:" + request.getCommand());
		System.out.println("sender:" + request.getSender());
		System.out.println("receiver:" + request.getReceiver());
		System.out.println("data:" + request.getData("message"));
		System.out.println("send_Date:" + request.getSend_Date());

		Response response = new Response();
		response.setFor_command(request.getCommand());
		response.setSend_Date(request.getSend_Date());

		database t = new database();
		String sendemail = null;
		String receiveemail = null;
		String emailpassword = null;
		String emailserver = null;
		String emailhost = null;

		MultiMailSenderInfo mailInfo = new MultiMailSenderInfo();
		MultiMailsender sms = new MultiMailsender();
		try {
			if (request.getData("message") == null) {
				if (t.IsUser(request.getReceiver())) {
					response.setResult(true);
					response.addData("response", "可以发送邮件");
				} else {
					response.addData("response", "对方不是本软件用户，无法获取到对方邮箱");
				}

			}

			if (request.getData("message") != null) {
				if (t.IsUser(request.getReceiver())) {
					sendemail = t.getemail(request.getSender());
					emailpassword = t.getemailPassword(request.getSender());
					receiveemail = t.getemail(request.getReceiver());
					emailserver = sendemail.substring(sendemail.indexOf("@") + 1, sendemail.indexOf("."));
					emailhost = "smtp." + emailserver + ".com";
					System.out.println("邮箱服务" + emailhost);
					mailInfo.setMailSender(emailhost, sendemail, emailpassword, receiveemail);
					mailInfo.setMailContents(request.getSender(), request.getData("message"));

					boolean result=sms.sendTextMail(mailInfo);

					if (result==true) {
						response.setResult(true);
						response.addData("response", "发送邮件成功");
					} else {
						response.addData("response", "发送邮件失败");
					}

				} else {
					System.out.println("对方不是本软件用户，无法获取到对方邮箱");
					response.addData("response", "对方不是本软件用户，无法获取到对方邮箱");

				}

			}
		} catch (SQLException e) {

		}

		return response;
	}
}
